﻿Imports System.Net
Imports System.Data
Imports System.Xml
Imports System.IO
Imports System.Text
Imports System.Windows.Controls
Imports System.Threading
Imports System.ComponentModel

Public Class SaveAllResultsWindow

    Private _resultsDS As DataSet
    Private _username As String
    Private _password As String
    Private _domain As String
    Private _url As String
    Private _startAt As String
    Private _countResults As String
    Private _SearchService As SearchService.QueryService
    Private _numTotalResults As String
    Private _intEndResultsShowing As Integer
    'Private _wsQueryType As WSQueryType
    Private _query As String
    Private _worker As BackgroundWorker


    Public Property Query() As String
        Get
            Return _query
        End Get
        Set(ByVal value As String)
            _query = value
            Me.txtQueryBox.Text = value
        End Set
    End Property

    Public Property Username As String
        Get
            Return _username
        End Get
        Set(ByVal value As String)
            _username = value
        End Set
    End Property

    Public Property Password As String
        Get
            Return _password
        End Get
        Set(ByVal value As String)
            _password = value
        End Set
    End Property

    Public Property Domain As String
        Get
            Return _domain
        End Get
        Set(ByVal value As String)
            _domain = value
        End Set
    End Property

    Public Property WebserviceUrl As String
        Get
            Return _url
        End Get
        Set(ByVal value As String)
            _url = value
        End Set
    End Property

    Public Property NumTotalResults As String
        Get
            Return _numTotalResults
        End Get
        Set(ByVal value As String)
            _numTotalResults = value
            Me.lblTotalRows.Content = value
        End Set
    End Property

    Private Sub btnRunAll_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRunAll.Click

        Me.Cursor = Cursors.Wait

        InitWS()

        Dim intTotalResults As Integer = CInt(_numTotalResults)
        Dim intResultsPerTrip As Integer = CInt(Me.txtResultsPerTrip.Text)
        Dim intStartAt As Integer = 1
        Dim intWaitTime As Integer = CInt(Me.txtWaitTime.Text)
        Dim fileName As String = Me.txtFileName.Text

        Dim resultsXDoc As XDocument = XDocument.Parse("<root></root>")

        Me.ProgressBar1.Minimum = 1
        Me.ProgressBar1.Maximum = 100

        _worker = New BackgroundWorker()
        _worker.WorkerReportsProgress = True
        _worker.WorkerSupportsCancellation = True

        AddHandler _worker.DoWork,
            Function(s, args)
                Dim worker2 As BackgroundWorker = TryCast(s, BackgroundWorker)

                While intStartAt < intTotalResults
                    worker2.ReportProgress((intStartAt / intTotalResults) * 100)

                    Dim queryXDoc As XDocument = XDocument.Parse(_query)
                    queryXDoc.Element("QueryPacket").Element("Query").Element("Range").Element("StartAt").Value = intStartAt
                    queryXDoc.Element("QueryPacket").Element("Query").Element("Range").Element("Count").Value = intResultsPerTrip

                    Dim queryResultsDS As DataSet = _SearchService.QueryEx(queryXDoc.ToString)
                    Dim queryResultsXDoc As XDocument = XDocument.Parse(queryResultsDS.GetXml())

                    resultsXDoc.Document.Root.Add(queryResultsXDoc.Document.Root.Elements("RelevantResults"))
                    intStartAt = intStartAt + intResultsPerTrip

                    System.Threading.Thread.Sleep(intWaitTime * 1000)

                End While

                resultsXDoc.Save(fileName)

                Return Nothing
            End Function

        AddHandler _worker.ProgressChanged,
                Function(s, args)
                    Me.ProgressBar1.Value = args.ProgressPercentage
                    Me.lblStatus.Content = "Retrieving results: " & CStr(intStartAt) & " - " & CStr(intStartAt + intResultsPerTrip)
                    Return Nothing
                End Function

        AddHandler _worker.RunWorkerCompleted,
                Function(s, arg)
                    Me.ProgressBar1.Value = 100
                    lblStatus.Content = "Completed"
                    btnRunAll.IsEnabled = True
                    Return Nothing
                End Function

        Me.btnRunAll.IsEnabled = False
        _worker.RunWorkerAsync()


        Me.Cursor = Cursors.Arrow

    End Sub

    Private Sub UpdateProgress(ByVal newValue As Integer)

    End Sub

    Private Sub InitWS()
        Dim creds As New System.Net.NetworkCredential(_username, _password, _domain)

        Dim site As String = Me._url.Trim()
        If site.EndsWith("/") Then
            site = site + "_vti_bin/search.asmx"
        Else
            site = site + "/_vti_bin/search.asmx"
        End If
        _SearchService = New SearchService.QueryService
        _SearchService.Url = site
        _SearchService.PreAuthenticate = True
        _SearchService.UseDefaultCredentials = False
        _SearchService.Credentials = creds

    End Sub


    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

    End Sub

    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnBrowse.Click
        Dim dlg As New Microsoft.Win32.SaveFileDialog()

        dlg.FileName = "AllResults"
        ' Default file name
        dlg.DefaultExt = ".xml"
        ' Default file extension
        dlg.Filter = "Results XML|*.xml"
        ' Filter files by extension
        ' Show save file dialog box
        Dim result As Nullable(Of Boolean) = dlg.ShowDialog()

        ' Process save file dialog box results
        If result = True Then
            ' Save document
            Dim filename As String = dlg.FileName
            Me.txtFileName.Text = filename
            '_resultsDS.WriteXml(filename)
        End If

    End Sub


End Class


